package util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
	private final static SessionFactory FACTORY = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		Configuration configuration=null;
		ServiceRegistry serviceRegistry=null;
		ServiceRegistryBuilder builder=null;
		SessionFactory factory=null;
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			configuration = new Configuration().configure();
			builder=new ServiceRegistryBuilder()
			            .applySettings(configuration.getProperties());
			serviceRegistry = builder.buildServiceRegistry();
			factory=configuration.buildSessionFactory(serviceRegistry);
			System.out.println(factory+" factory");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return factory;
	}

	public static SessionFactory getSessionFactory() {
		return FACTORY;
	}

	public static Session openSession() {
		return FACTORY.openSession();
	}

	public static void close(Session session) {
		if (session != null)
			session.close();
	}

	public static void main(String[] args) {// 测试方法
		getSessionFactory();
	}
}
